package com.monlyu.bo;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.poi.hwpf.HWPFDocument;
import org.apache.poi.hwpf.extractor.WordExtractor;
import org.apache.poi.poifs.filesystem.DirectoryNode;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
import org.hibernate.Criteria;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;
import org.springframework.stereotype.Repository;

import com.google.common.collect.Lists;
import com.monlyu.bean.Page;
import com.monlyu.bean.Pages;
import com.monlyu.exception.MsgException;
import com.monlyu.model.CountFGModel;
import com.monlyu.model.SearchManuscriptModel;
import com.monlyu.util.ArrayUtil;
import com.monlyu.util.DateUtil;
import com.monlyu.util.StringUtil;
import com.monlyu.util.WebOptUtil;
import com.monlyu.varables.PermVar;
import com.monlyu.vo.Attachment;
import com.monlyu.vo.Enums;
import com.monlyu.vo.GaoJian2Reporter;
import com.monlyu.vo.ManuScAudit;
import com.monlyu.vo.Manuscript;
import com.monlyu.vo.Manuscript2Image;
import com.monlyu.vo.SolutionContent;
import com.monlyu.vo.SolutionItem;
import com.monlyu.vo.User;

/*******************************************************************************
 * <b>功能描述☞</b><br>
 * <b>项目名☞</b>NewsSys<br>
 * <b>文件路径☞</b>com.monlyu.bo.ManuscriptBo.java<br>
 * <b>开发日期☞</b>2010-2-23 <br>
 * 
 * @author skw
 * @since JDK 5
 * @version 1.0.1
 ******************************************************************************/
@Repository(value = "manuscriptBo")
public class ManuscriptBo extends BaseBo {

	private RoleBo roleBo;
	private MailBo mailBo;
	private AttachmentBo attachmentBo;
	private UserBo userBo;

	public void setUserBo(UserBo userBo) {
		this.userBo = userBo;
	}

	public void setMailBo(MailBo mailBo) {
		this.mailBo = mailBo;
	}

	public void setAttachmentBo(AttachmentBo attachmentBo) {
		this.attachmentBo = attachmentBo;
	}

	public RoleBo getRoleBo() {
		return roleBo;
	}

	public void setRoleBo(RoleBo roleBo) {
		this.roleBo = roleBo;
	}

	public void CreateManuscript(Manuscript manuscript, String str)
			throws Exception {
		// manuscript=decodeManuscript(manuscript);
		GaoJian2Reporter gaoJian2Reporter = new GaoJian2Reporter();
		manuscript.setAuditZt(Manuscript.STATUS_DRAFT);
		// boolean hasCheck = roleBo.checkPermission(PermVar.MS_ADUIT_ONE);
		// if (hasCheck) {
		// manuscript.setAuditZt(Manuscript.STATUS_AUDITING_TWO);
		// }
		// boolean hasCheck2 = roleBo.checkPermission(PermVar.MS_ADUIT_TWO);
		// if (hasCheck2) {
		// manuscript.setAuditZt(Manuscript.STATUS_AUDITING_THREE);
		// }
		// boolean hasCheck3 = roleBo.checkPermission(PermVar.MS_ADUIT_THREE);
		// if (hasCheck3) {
		// manuscript.setAuditZt(Manuscript.STATUS_DONE);
		// }
		if (!StringUtil.isEmpty(manuscript.getContent())
				&& manuscript.getContent().indexOf("【口播】") >= 0) {
			manuscript.setKouBo(true);
		} else {
			manuscript.setKouBo(false);
			manuscript.setDaoyu(getDetails(manuscript.getContent(), "daoyu"));
			manuscript.setBianhouyu(getDetails(manuscript.getContent(), "bhy"));
		}
		manuscript.setTimeLong(calcTimeLong(manuscript));
		manuscript.setUser(curUser());
		manuscript.setCreateDate(DateUtil.now());
		dao.insertOrUpdate(manuscript);
		// 加入联合撰稿人记录(撰稿人自己)
		gaoJian2Reporter.setManuscript(manuscript);
		gaoJian2Reporter.setReporter(curUser());

		dao.insertOrUpdate(gaoJian2Reporter);
		// 加入联合申报记者记录
		if (!StringUtil.killNull(str).equals("")) {
			String[] userIds = str.split(",");
			for (int i = 0; i <= userIds.length - 1; i++) {
				GaoJian2Reporter gj2u = new GaoJian2Reporter();
				gj2u.setReporter(dao.findOne(User.class, "id", Long
						.parseLong(userIds[i])));
				gj2u.setManuscript(manuscript);
				dao.insertOrUpdate(gj2u);
			}
		}
	}

	/**
	 * 提交审核
	 * 
	 * @param manuscript
	 */
	public void subAudit(Manuscript manuscript) {
		Manuscript dbmanuscript = dao.get(Manuscript.class, manuscript.getId());
		// System.out.println("manuscript.getId():" + manuscript.getId());
		// 在审核时再来根据权限判断应该保存为什么状态
		dbmanuscript.setAuditZt(Manuscript.STATUS_AUDITING_ONE);
		if (roleBo.checkPermission(PermVar.MS_ADUIT_ONE)) {
			dbmanuscript.setAuditZt(Manuscript.STATUS_AUDITING_TWO);
		}
		if (roleBo.checkPermission(PermVar.MS_ADUIT_TWO)) {
			dbmanuscript.setAuditZt(Manuscript.STATUS_AUDITING_THREE);
		}
		if (roleBo.checkPermission(PermVar.MS_ADUIT_THREE)) {
			dbmanuscript.setAuditZt(Manuscript.STATUS_DONE);
		}
		dao.update(dbmanuscript);
	}

	/**
	 * 更新稿件
	 * 
	 * @param manuscript
	 * @throws Exception
	 */
	public void UpdateManuscript(Manuscript manuscript, String str)
			throws Exception {
		Manuscript dbmanuscript = dao.get(Manuscript.class, manuscript.getId());
		dbmanuscript.setTitle(manuscript.getTitle());
		dbmanuscript.setContent(manuscript.getContent());
		dbmanuscript.setBcType(manuscript.getBcType());
		dbmanuscript.setColumn(manuscript.getColumn());
		dbmanuscript.setOwetype(manuscript.getOwetype());
		dbmanuscript.setRemark(manuscript.getRemark());
		dbmanuscript.setUnit(manuscript.getUnit());
		dbmanuscript.setWhere(manuscript.getWhere());
		if (!StringUtil.isEmpty(manuscript.getContent())
				&& manuscript.getContent().indexOf("【口播】") > 0) {
			dbmanuscript.setKouBo(true);
			dbmanuscript.setDaoyu(null);
			dbmanuscript.setBianhouyu(null);
		} else {
			dbmanuscript.setKouBo(false);
			dbmanuscript.setDaoyu(getDetails(manuscript.getContent(), "daoyu"));
			dbmanuscript
					.setBianhouyu(getDetails(manuscript.getContent(), "bhy"));
		}
		dbmanuscript.setTimeLong(calcTimeLong(dbmanuscript));
		dao.update(dbmanuscript);

		// 加入联合申报记者记录(如果选错了修改怎么办?????????)
		// 先删除GaoJian2Reporter中非撰稿人的记录(manuscript关联)，重新插入新纪录

		// String hql="Delete from GaoJian2Reporter where
		// manuscript.id="+manuscript.getId()+" and
		// reporter.id<>"+curUser().getId() ;
		// dao.execute(hql);
		// 删除旧的
		String hql = "select g.id from com.monlyu.vo.GaoJian2Reporter as g where g.reporter.id<>"
				+ curUser().getId()
				+ "and g.manuscript.id="
				+ manuscript.getId();
		List<Long> list = new ArrayList<Long>();
		list = dao.find(hql);
		for (Long i : list) {
			deleteG2r(i);
		}
		// 插入新的
		if (!StringUtil.killNull(str).equals("")) {
			String[] userIds = str.split(",");
			for (int i = 0; i <= userIds.length - 1; i++) {
				GaoJian2Reporter gj2u = new GaoJian2Reporter();
				gj2u.setReporter(dao.findOne(User.class, "id", Long
						.parseLong(userIds[i])));
				gj2u.setManuscript(manuscript);
				dao.insertOrUpdate(gj2u);
			}
		}
	}

	public void deleteG2r(long id) {
		dao.delete(GaoJian2Reporter.class, id);
	}

	/**
	 * 审核稿件
	 * 
	 * @param manuscript
	 * @throws Exception
	 */
	public void AuditManuscript(Manuscript manuscript, ManuScAudit manuScAudit,
			String str) throws Exception {
		Manuscript dbmanuscript = dao.get(Manuscript.class, manuscript.getId());
		manuScAudit.setContent(dbmanuscript.getContent());
		dbmanuscript.setTitle(manuscript.getTitle());
		dbmanuscript.setContent(manuscript.getContent());
		dbmanuscript.setBcType(manuscript.getBcType());
		dbmanuscript.setColumn(manuscript.getColumn());
		dbmanuscript.setOwetype(manuscript.getOwetype());
		dbmanuscript.setRemark(manuscript.getRemark());
		dbmanuscript.setUnit(manuscript.getUnit());
		dbmanuscript.setWhere(manuscript.getWhere());
		if (manuscript.getAuditUser() != null
				&& manuscript.getAuditUser().getId() > 0) {
			dbmanuscript.setAuditUser(dao.get(User.class, manuscript
					.getAuditUser().getId()));
		} else {
			dbmanuscript.setAuditUser(null);
		}
		if (!StringUtil.isEmpty(manuscript.getContent())
				&& manuscript.getContent().indexOf("【口播】") > 0) {
			dbmanuscript.setKouBo(true);
			dbmanuscript.setDaoyu(null);
			dbmanuscript.setBianhouyu(null);
		} else {
			dbmanuscript.setKouBo(false);
			dbmanuscript.setDaoyu(getDetails(manuscript.getContent(), "daoyu"));
			dbmanuscript
					.setBianhouyu(getDetails(manuscript.getContent(), "bhy"));
		}
		// dbmanuscript.setDaoyu(getDetails(manuscript.getContent(), "daoyu"));
		// dbmanuscript.setBianhouyu(getDetails(manuscript.getContent(),
		// "bhy"));
		dbmanuscript.setTimeLong(calcTimeLong(dbmanuscript));
		int zt = dbmanuscript.getAuditZt();
		final String mail_title = "稿件[%s]的[%s]结果通知";
		final String mail_content = "您标题为[%s]的稿件，在[%s]过程中，被[%s]审核通过。<br/> 审核意见：%s";
		String shenhe = "终审";
		boolean flag = false;
		if (zt == Manuscript.STATUS_AUDITING_ONE) {
			if (roleBo.checkPermission(PermVar.MS_ADUIT_ONE)) {
				dbmanuscript.setAuditZt(Manuscript.STATUS_AUDITING_TWO);
				flag = true;
			}
			if (roleBo.checkPermission(PermVar.MS_ADUIT_TWO)) {
				dbmanuscript.setAuditZt(Manuscript.STATUS_AUDITING_THREE);
				flag = true;
			}
			if (roleBo.checkPermission(PermVar.MS_ADUIT_THREE)) {
				dbmanuscript.setAuditZt(Manuscript.STATUS_DONE);
				flag = true;
			}
			shenhe = "一审";
		} else if (zt == Manuscript.STATUS_AUDITING_TWO) {
			shenhe = "二审";
			if (roleBo.checkPermission(PermVar.MS_ADUIT_TWO)) {
				dbmanuscript.setAuditZt(Manuscript.STATUS_AUDITING_THREE);
				flag = true;
			}
			if (roleBo.checkPermission(PermVar.MS_ADUIT_THREE)) {
				dbmanuscript.setAuditZt(Manuscript.STATUS_DONE);
				flag = true;
			}
		} else {
			if (roleBo.checkPermission(PermVar.MS_ADUIT_THREE)) {
				dbmanuscript.setAuditZt(Manuscript.STATUS_DONE);
				flag = true;
			}
		}
		if (!flag) {
			throw new MsgException("对不起，您的审核权限不够！");
		}
		final String send_mail_content = String.format(mail_title, manuscript
				.getTitle(), shenhe);
		mailBo.sendMail(send_mail_content, String.format(mail_content,
				dbmanuscript.getTitle(), shenhe, curUser().getName(),
				manuScAudit.getRemark()), dbmanuscript.getUser().getId());

		manuScAudit.setAuditor(curUser());
		manuScAudit.setDate(DateUtil.now());
		manuScAudit.setManuscript(manuscript);
		manuScAudit.setLevel(zt);
		// 删除旧的共同撰稿人
		String hql = "select g.id from com.monlyu.vo.GaoJian2Reporter as g where g.reporter.id<>"
				+ curUser().getId()
				+ "and g.manuscript.id="
				+ manuscript.getId();
		List<Long> list = new ArrayList<Long>();
		list = dao.find(hql);
		for (Long i : list) {
			deleteG2r(i);
		}
		// 插入新的共同撰稿人
		if (!StringUtil.killNull(str).equals("")) {
			String[] userIds = str.split(",");
			for (int i = 0; i <= userIds.length - 1; i++) {
				GaoJian2Reporter gj2u = new GaoJian2Reporter();
				gj2u.setReporter(dao.findOne(User.class, "id", Long
						.parseLong(userIds[i])));
				gj2u.setManuscript(manuscript);
				dao.insertOrUpdate(gj2u);
			}
		}
		dao.insertOrUpdate(manuScAudit);
		// 如果审核完毕，则不需要再设置上级审核人员
		if (dbmanuscript.getAuditZt() == Manuscript.STATUS_DONE) {
			dbmanuscript.setAuditUser(null);
		}
		dao.update(dbmanuscript);
	}

	/**
	 * 查询可审核稿件
	 * 
	 * @param page
	 * @return
	 */
	public Pages<Manuscript> getManuscripts(Page page) {
		Criteria criteria = dao.initCriteria(Manuscript.class);
		// 没有审核权限的人只能查询到自己的稿件（审核中的稿件前台控制使其不能编辑上传）
		// 一审权限的人只能看到一审中和自己的；二审权限的只能看到二审中和自己的；2权限都有的可看到一审、二审中和自己的；没审核权限的只能看到自己的
		boolean hasCheck = roleBo.checkPermission(PermVar.MS_ADUIT_ONE);
		boolean hasCheck2 = roleBo.checkPermission(PermVar.MS_ADUIT_TWO);
		boolean hasCheck3 = roleBo.checkPermission(PermVar.MS_ADUIT_THREE);
		if ((hasCheck && hasCheck2) && hasCheck3) {
			criteria.add(Restrictions.in("auditZt", new Object[] {
					Manuscript.STATUS_AUDITING_ONE,
					Manuscript.STATUS_AUDITING_TWO,
					Manuscript.STATUS_AUDITING_THREE }));
		} else if (!hasCheck && hasCheck2 && hasCheck3) {
			criteria.add(Restrictions.in("auditZt", new Object[] {
					Manuscript.STATUS_AUDITING_TWO,
					Manuscript.STATUS_AUDITING_THREE }));
		} else if (hasCheck && !hasCheck2 && hasCheck3) {
			criteria.add(Restrictions.in("auditZt", new Object[] {
					Manuscript.STATUS_AUDITING_ONE,
					Manuscript.STATUS_AUDITING_THREE }));
		} else if (hasCheck && hasCheck2 && !hasCheck3) {
			criteria.add(Restrictions.in("auditZt", new Object[] {
					Manuscript.STATUS_AUDITING_TWO,
					Manuscript.STATUS_AUDITING_ONE }));
		} else if (!hasCheck && !hasCheck2 && hasCheck3) {
			criteria.add(Restrictions.eq("auditZt",
					Manuscript.STATUS_AUDITING_THREE));
		} else if (!hasCheck && hasCheck2 && !hasCheck3) {
			criteria.add(Restrictions.eq("auditZt",
					Manuscript.STATUS_AUDITING_TWO));
		} else if (hasCheck && !hasCheck2 && !hasCheck3) {
			criteria.add(Restrictions.eq("auditZt",
					Manuscript.STATUS_AUDITING_ONE));
		} else {
			// criteria.add(Restrictions.eq("user", curUser()));
			throw new MsgException("对不起，您没有稿件审核的权限。");
		}
		// 只能查询出需要自己审核的稿件或者没有设置审核人员的稿件
		criteria.add(Restrictions.or(Restrictions.eq("auditUser.id", curUser()
				.getId()), Restrictions.isNull("auditUser.id")));
		criteria.add(Restrictions.eq("adv", false));
		return findByCriteria(page.getNo(), page.getSize(), criteria);

	}

	/**
	 * 查询自己的可编辑稿件
	 * 
	 * @param page
	 * @return
	 */

	public Pages<Manuscript> getEditable(Page page) {
		Criteria criteria = dao.initCriteria(Manuscript.class);
		criteria.add(Restrictions.eq("user", curUser()));
		criteria.add(Restrictions.eq("auditZt", Manuscript.STATUS_DRAFT));
		criteria.add(Restrictions.eq("adv", false));
		return findByCriteria(page.getNo(), page.getSize(), criteria);
	}

	/**
	 * 查询已审核稿件
	 * 
	 * @param page
	 * @return
	 */

	public Pages<Manuscript> getDoneEditable(Page page) {
		Criteria criteria = dao.initCriteria(Manuscript.class);
		criteria.add(Restrictions.eq("auditZt", Manuscript.STATUS_DONE));
		criteria.add(Restrictions.eq("adv", false));
		criteria.addOrder(Order.desc("id"));
		return findByCriteria(page.getNo(), page.getSize(), criteria);
	}

	public void delete(Manuscript manuscript) {
		List<GaoJian2Reporter> g2r = dao.find(GaoJian2Reporter.class,
				"manuscript.id", manuscript.getId());
		for (GaoJian2Reporter gaoJian2Reporter : g2r) {
			dao.delete(GaoJian2Reporter.class, gaoJian2Reporter.getId());
		}
		List<Manuscript2Image> is = dao.find(Manuscript2Image.class,
				"manuscript.id", manuscript.getId());
		for (Manuscript2Image image : is) {
			attachmentBo.deleteFile(image.getImageId());
			dao.delete(image);
		}
		dao.delete(Manuscript.class, manuscript.getId());
	}

	/**
	 * 毙稿
	 * 
	 * @param manuscript
	 * @param manuScAudit2
	 */
	public void killMas(Manuscript manuscript, ManuScAudit manuScAudit) {
		Manuscript dbmanuscript = dao.get(Manuscript.class, manuscript.getId());
		// System.out.println("manuscript.getId():" + manuscript.getId());
		int zt = dbmanuscript.getAuditZt();
		dbmanuscript.setAuditZt(Manuscript.STATUS_KILLED);
		// 插入审核记录
		manuScAudit.setAuditor(curUser());
		manuScAudit.setDate(DateUtil.now());
		manuScAudit.setManuscript(manuscript);
		manuScAudit.setLevel(zt);
		manuScAudit.setKilled(true);
		dao.insertOrUpdate(manuScAudit);
		dao.update(dbmanuscript);

		String content = String.format(
				"您标题为[%s]的稿件，在[%s]审核过程中，被[%s]毙稿<br/>原因：%s", dbmanuscript
						.getTitle(), zt, curUser().getName(), manuScAudit
						.getRemark());
		mailBo.sendMail(String
				.format("稿件[%s]毙稿通知", dbmanuscript.eclipseTitle()), content,
				dbmanuscript.getUser().getId());
	}

	/**
	 * 返回给撰稿人
	 * 
	 * @param manuscript
	 * @param manuScAudit2
	 */
	public void returnToApp(Manuscript manuscript, ManuScAudit manuScAudit) {
		Manuscript dbmanuscript = dao.get(Manuscript.class, manuscript.getId());
		// System.out.println("manuscript.getId():" + manuscript.getId());
		int zt = dbmanuscript.getAuditZt();
		dbmanuscript.setAuditZt(Manuscript.STATUS_DRAFT);
		// 插入审核记录
		manuScAudit.setAuditor(curUser());
		manuScAudit.setDate(DateUtil.now());
		manuScAudit.setManuscript(manuscript);
		manuScAudit.setLevel(zt);
		manuScAudit.setSendBack(true);
		dao.insertOrUpdate(manuScAudit);
		dao.update(dbmanuscript);

		String content = String.format(
				"您标题为[%s]的稿件，在[%s]审核过程中，被[%s]打回<br/> 原因：%s", manuscript
						.getTitle(), zt, curUser().getName(), manuScAudit
						.getRemark());
		mailBo.sendMail(String
				.format("退还稿件[%s]通知", dbmanuscript.eclipseTitle()), content,
				dbmanuscript.getUser().getId());
	}

	/**
	 * 查询供选择的联合撰稿记者
	 * 
	 * @return
	 */
	public List<User> getAllRepUser() {
		long id = curUser().getId();
		String hql = "from com.monlyu.vo.User u where u.enable=true and u.id<>"
				+ id + " order by u.name";
		return dao.find(hql);
	}

	/**
	 * 查询数据库中联合撰稿人 根据稿件<br>
	 * 
	 * @modify Chendan 查询稿件所有记者，便于直接看到稿件的所有记者
	 * @param manuscript
	 * @return
	 */
	public String getDbLhbdjzName(Manuscript manuscript) {
		String str = "";
		String hql = "select reporter.name from com.monlyu.vo.GaoJian2Reporter where "
				+ " manuscript.id="
				+ manuscript.getId()
				+ "and reporter.id<>"
				+ curUser().getId() + " order by reporter.name";
		List<String> list = dao.find(hql);
		for (String s : list) {
			str += s.toString();
			str += ",";

		}
		if (str.equals("")) {
			return "";
		} else {
			return (String) StringUtil.shot(str, str.length() - 1);
		}
	}

	public String getDbLhbdjzId(Manuscript manuscript) {
		String str = "";
		String hql = "select reporter.id from com.monlyu.vo.GaoJian2Reporter where "
				+ " manuscript.id="
				+ manuscript.getId()
				+ "and reporter.id<>"
				+ curUser().getId() + " order by reporter.name";
		List<Long> list = dao.find(hql);
		for (Long s : list) {
			str += s.toString();
			str += ",";

		}
		if (str.equals("")) {
			return "";
		} else {
			return (String) StringUtil.shot(str, str.length() - 1);
		}
	}

	public List<ManuScAudit> getAuditRecd(Manuscript manuscript) {
		String hql = "from com.monlyu.vo.ManuScAudit where manuscript.id="
				+ manuscript.getId();
		return dao.find(hql);
	}

	/**
	 * 获取稿件指定修改记录的内容
	 * 
	 * @param manuscript
	 * @param level
	 *            原稿0，一审1，二审2，三审3
	 * @return
	 * @since chendan 2010-3-27
	 */
	public String getMsContent(Manuscript manuscript, int level) {
		if (level < manuscript.getAuditZt() - 1) {
			String hql = "from com.monlyu.vo.ManuScAudit m where manuscript.id=? and m.level=?";
			Object result = dao.findOne(hql, new Object[] { manuscript.getId(),
					level + 1 });
			if (result != null) {
				return ((ManuScAudit) result).getContent();
			}
			return "";
		} else {
			return manuscript.getContent();
		}
	}

	/**
	 * 比较两次稿件的不同地方
	 * 
	 * @param manuscript
	 * @param level1
	 * @param level2
	 * @return
	 * @since chendan 2010-3-27
	 */
	public String compareContent(Manuscript manuscript, int level1, int level2) {
		String source = getMsContent(manuscript, level1);
		String desc = getMsContent(manuscript, level2);
		source = source.replaceAll("\\\r", "<p>");
		desc = desc.replaceAll("\\\r", "<p>");
		return StringUtil.compStringByP(source, desc);
	}

	/**
	 * 读取导语、编后语等
	 * 
	 * @param str
	 * @return
	 */
	public String getDetails(String content, String str) {
		if (str.equals("daoyu")) {
			return StringUtil.trim(getSubString(content, "【导语】", "【"));
		} else if (str.equals("bhy")) {
			return StringUtil.trim(getSubString(content, "【编后语】", "【"));
		} else if (str.equals("zw")) {
			return StringUtil.trim(getSubString(content, "【正文】", "【"));
		} else {
			return "";
		}
	}

	/**
	 * 根据设置计算稿件时长
	 * 
	 * @param manuscript
	 * @return 总秒数
	 */
	public long calcTimeLong(Manuscript manuscript) {
		String content = getDetails(manuscript.getContent(), "zw");
		long len = content.length();
		long t = len / ((Long.valueOf(getTimeLongUnit())) / 60);
		return t;
	}

	public String getTimeLongUnit() {
		String hql = "select e.key from com.monlyu.vo.Enums e where e.type='msTimeSet.type'";
		return dao.find(hql).get(0).toString();
	}

	public void saveTimeLongUnit(String args) {
		String hql = "update com.monlyu.vo.Enums e set e.key=? where e.type='msTimeSet.type'";
		dao.execute(hql, args);
	}

	/**
	 * 截取字符串
	 * 
	 * @param str
	 * @return
	 */

	public String getSubString(String str, String start, String end) {
		StringBuffer rtn = new StringBuffer();
		int idxS = str.indexOf(start);
		int idxE = str.indexOf(end, idxS + 1);
		while (idxS != -1) {
			if (idxS != -1 && idxE == -1) {
				idxE = str.length();
			}
			rtn.append("\r").append(str.substring(idxS + start.length(), idxE));
			str = str.substring(idxE);
			idxS = str.indexOf(start);
			idxE = str.indexOf(end, idxS + 1);

		}
		return rtn.toString();
	}

	/**
	 * @param searchManuscriptModel
	 * @return
	 */

	public List<Manuscript> getManuscriptByModel(
			SearchManuscriptModel searchManuscriptModel) {
		StringBuilder hql = new StringBuilder();
		List<Object> args = new ArrayList<Object>();
		hql.append("from com.monlyu.vo.Manuscript m where m.adv=false ");
		if (searchManuscriptModel != null) {
			if (searchManuscriptModel.getUserId() > 0) {
				hql
						.append(" and exists(select g.id from com.monlyu.vo.GaoJian2Reporter g "
								+ "where g.manuscript.id=m.id and  g.reporter.id=?) ");
				args.add(searchManuscriptModel.getUserId());
			}
			if (searchManuscriptModel.getColumn() != null
					&& searchManuscriptModel.getColumn().intValue() > 0) {
				hql.append(" and m.column=?");
				args.add(searchManuscriptModel.getColumn());
			}
			if (searchManuscriptModel.getBeginDate() != null) {
				hql.append(" and m.createDate>=?");
				args.add(searchManuscriptModel.getBeginDate());
			}
			if (searchManuscriptModel.getEndDate() != null) {
				hql.append(" and m.createDate<=?");
				args
						.add(DateUtil.addDay(
								searchManuscriptModel.getEndDate(), 1));
			}
			if (searchManuscriptModel.getUbeginDate() != null) {
				hql.append(" and m.usedDate>=?");
				args.add(searchManuscriptModel.getUbeginDate());
			}
			if (searchManuscriptModel.getUendDate() != null) {
				hql.append(" and m.usedDate<=?");
				args.add(DateUtil
						.addDay(searchManuscriptModel.getUendDate(), 1));
			}
			if (searchManuscriptModel.getOwetype() != null
					&& searchManuscriptModel.getOwetype().intValue() > 0) {
				hql.append(" and m.owetype=?");
				args.add(searchManuscriptModel.getOwetype());
			}
			if (searchManuscriptModel.getCategory() != null
					&& searchManuscriptModel.getCategory().intValue() > 0) {
				hql.append(" and m.category=?");
				args.add(searchManuscriptModel.getCategory());
			}
			if (searchManuscriptModel.getBcType() != null
					&& searchManuscriptModel.getBcType().intValue() > 0) {
				hql.append(" and m.bcType=?");
				args.add(searchManuscriptModel.getBcType());
			}
			if (!StringUtil.isEmpty(searchManuscriptModel.getTitle())) {
				hql.append(" and (m.title like ? or m.content like ?)");
				args.add("%" + searchManuscriptModel.getTitle() + "%");
				args.add("%" + searchManuscriptModel.getTitle() + "%");
			}
		}
		return dao.find(hql.toString(), args.toArray());
	}

	/**
	 * 设置稿件的使用时间
	 * 
	 * @param manuscript
	 * @since ChenDan 2010-8-7
	 */
	public void setMansUsedDate(Manuscript manuscript) {
		// 稿件已被使用且没有记录使用时间的时候，记录当前时间
		if (manuscript.getTimes() > 0 && manuscript.getUsedDate() == null) {
			manuscript.setUsedDate(DateUtil.now());
		} else if (manuscript.getTimes() == 0) {
			// 稿件未被使用或者被取消使用
			manuscript.setUsedDate(null);
		}
	}

	/**
	 * 查询稿件所有的撰稿人
	 * 
	 * @param manuscript
	 * @return
	 * @since chendan 2010-6-1
	 */
	public String getDbLhbdjzName1(Manuscript manuscript) {
		String str = "";
		String hql = "select reporter.name from com.monlyu.vo.GaoJian2Reporter where "
				+ " manuscript.id="
				+ manuscript.getId()
				+ " order by reporter.name";
		List<String> list = dao.find(hql);
		for (String s : list) {
			str += s.toString();
			str += ",";

		}
		if (str.equals("")) {
			return "";
		} else {
			return (String) StringUtil.shot(str, str.length() - 1);
		}
	}

	/**
	 * 组装成对象，便于页面显示，将每个稿件的所有记录显示到一条记录中
	 * 
	 * @param qm
	 * @return
	 * @since chendan 2010-6-1
	 */
	public List<CountFGModel> getCountFGModelByModel(
			SearchManuscriptModel smModel) {
		List<Manuscript> results = getManuscriptByModel(smModel);
		List<CountFGModel> countList = Lists.newArrayList();
		for (Manuscript manuscript : results) {
			CountFGModel countFGModel = new CountFGModel();
			countFGModel.setManuscript(manuscript);
			countFGModel.setUserName(getDbLhbdjzName1(manuscript));
			countList.add(countFGModel);
		}
		return countList;

	}

	/**
	 * ********************************
	 * 以下方法未用*****************************************
	 */

	/**
	 * 撰稿decode
	 * 
	 * @param manuscript
	 * @throws Exception
	 */
	public Manuscript decodeManuscript(Manuscript manuscript) throws Exception {
		manuscript.setTitle(URLDecoder.decode(manuscript.getTitle(), "UTF-8"));
		manuscript.setDaoyu(URLDecoder.decode(manuscript.getDaoyu(), "UTF-8"));
		manuscript.setBianhouyu(URLDecoder.decode(manuscript.getBianhouyu(),
				"UTF-8"));
		manuscript
				.setRemark(URLDecoder.decode(manuscript.getRemark(), "UTF-8"));
		return manuscript;

	}

	/**
	 * 解析doc
	 * 
	 * @param file
	 * @return
	 * @throws IOException
	 */
	public String readContent(File file) throws IOException {
		FileInputStream fis = null;
		try {
			fis = new FileInputStream(file);
			POIFSFileSystem poifsFileSystem = new POIFSFileSystem(fis);
			DirectoryNode directoryNode = poifsFileSystem.getRoot();
			HWPFDocument hwpf = new HWPFDocument(directoryNode, poifsFileSystem);
			WordExtractor wordExtractor = new WordExtractor(hwpf);

			return wordExtractor.getText();
		} finally {
			if (fis != null) {
				fis.close();
			}
		}
	}

	/**
	 * 字符串截取
	 * 
	 * @param str
	 *            要截取的字符串
	 * @param open
	 *            开始字符串
	 * @param close
	 *            结束字符串
	 * @return
	 */
	public static String substringBetween(String str, String open, String close) {
		if ((str == null) || (open == null)) {
			return null;
		}
		int start = str.indexOf(open) + open.length();
		return substringBetween(str, start, close);
	}

	/**
	 * 字符串截取
	 * 
	 * @param str
	 *            要截取的字符串
	 * @param start
	 *            开始索引
	 * @param close
	 *            结束字符串
	 * @return
	 */
	public static String substringBetween(String str, int start, String close) {
		if ((str == null) || (str.length() < start) || (start <= -1)
				|| (close == null)) {
			return null;
		}
		int end = str.indexOf(close, start);
		if (end != -1) {
			return str.substring(start, end);
		}
		return null;
	}

	public void insertImage(Manuscript manuscript, String mimages) {
		String[] images = mimages.split(",");
		for (String image : images) {
			if (!StringUtil.isTrimEmpty(image)) {
				Manuscript2Image m2i = new Manuscript2Image();
				m2i.setImageId(Long.parseLong(image));
				m2i.setManuscript(manuscript);
				dao.insertOrUpdate(m2i);
			}
		}
	}

	public List<Manuscript2Image> findAllImage(Manuscript manuscript) {
		List<Manuscript2Image> all = dao.find(Manuscript2Image.class,
				"manuscript.id", manuscript.getId());
		for (Manuscript2Image manuscript2Image : all) {
			Attachment attachment = dao.get(Attachment.class, manuscript2Image
					.getImageId());
			if (attachment != null) {
				manuscript2Image.setMark(attachment.getMark());
				manuscript2Image.setPath(ArrayUtil.pathJoin(WebOptUtil.APP_ARGS
						.getWebRelUrl(), "common", "upload")
						+ attachment.smallview());
				manuscript2Image.setPath(StringUtil.path2Uri(manuscript2Image.getPath()));
			}
		}
		return all;
	}

	public void update(Manuscript manuscript, String inimages) {
		dao.delete(dao.find(Manuscript2Image.class, "manuscript.id", manuscript
				.getId()));
		insertImage(manuscript, inimages);
	}

	public void deleteM2I(Manuscript manuscript) {
		List<Manuscript2Image> is = dao.find(Manuscript2Image.class,
				"manuscript.id", manuscript.getId());
		for (Manuscript2Image image : is) {
			attachmentBo.deleteFile(image.getImageId());
			dao.delete(image);
		}

	}

	public void deleteReferce(String imagesId, Manuscript manuscript) {
		if (manuscript != null && manuscript.getId() != null) {
			Criteria criteria = dao.initCriteria(Manuscript2Image.class);
			criteria.add(Restrictions.eq("imageId", Long.parseLong(imagesId)));
			criteria.add(Restrictions.eq("manuscript.id", manuscript.getId()));
			dao.delete(criteria.list());
		}
		attachmentBo.deleteFile(Long.parseLong(imagesId));
	}

	/**
	 * 查找可用的文稿
	 * 
	 * @param b
	 * @return
	 */
	public List<Manuscript> findValidScript(boolean isValid) {
		Criteria criteria = dao.initCriteria(Manuscript.class);
		criteria.add(Restrictions.eq("auditZt", Manuscript.STATUS_DONE));
		List<SolutionContent> lists = dao.find(SolutionContent.class);
		List<Long> ids = new ArrayList<Long>();
		for (SolutionContent sc : lists) {
			ids.add(sc.getManuscript().getId());
		}
		if (ids != null && ids.size() > 0) {
			if (isValid) {
				criteria.add(Restrictions.not(Restrictions.in("id", ids)));
			} else {
				criteria.add(Restrictions.in("id", ids));
			}
		}
		return criteria.list();
	}

	public Map<String, List<Manuscript>> findScript(String[] ids) {
		List<Long> mid = ArrayUtil.str2Long(ids);
		List<Manuscript> all = dao.get(Manuscript.class, "id", mid);
		Map<String, List<Manuscript>> reslut = new HashMap<String, List<Manuscript>>();
		for (Manuscript manuscript : all) {
			Enums e = dao.get(Enums.class, manuscript.getColumn());
			String key = e.getKey();
			List<Manuscript> input = reslut.get(key);
			if (input == null) {
				input = new ArrayList<Manuscript>();
			}
			input.add(manuscript);
			reslut.put(key, input);
		}
		return reslut;
	}

	/**
	 * 通过Id去查找对应的董小
	 * 
	 * @param id
	 * @return
	 */
	public Map<String, List<Manuscript>> findScript(Long id) {
		Criteria items = dao.initCriteria(SolutionItem.class);
		items.add(Restrictions.eq("solution.id", id));
		items.add(Restrictions.gt("order", 2));
		items.addOrder(Order.asc("order"));

		String hql = "select manuscript.id from com.monlyu.vo.SolutionContent m where m.solutionItem.id in ";

		// dao.find("select SolutionContent", args);

		return null;
	}

	/**
	 * 获取审核人员列表
	 * 
	 * @param auditZt
	 * @return
	 * @since chendan 2011-7-26
	 */
	public HashMap getAuditUser(int auditZt) {
		boolean hasCheck1 = roleBo.checkPermission(PermVar.MS_ADUIT_ONE);
		boolean hasCheck2 = roleBo.checkPermission(PermVar.MS_ADUIT_TWO);
		boolean hasCheck3 = roleBo.checkPermission(PermVar.MS_ADUIT_THREE);
		// 查询的审核人员审核权限要高于当前用户权限
		String permissionId = hasCheck1 ? PermVar.MS_ADUIT_TWO
				: hasCheck2 ? PermVar.MS_ADUIT_THREE : hasCheck3 ? ""
						: PermVar.MS_ADUIT_ONE;
		if (auditZt == 1) {
			permissionId = PermVar.MS_ADUIT_TWO;
			if (hasCheck2) {
				permissionId = PermVar.MS_ADUIT_THREE;
			}
		} else if (auditZt == 2) {
			permissionId = PermVar.MS_ADUIT_THREE;
		} else if (auditZt == 3) {
			permissionId = "";
		}
		List<User> users = userBo.getUserByPermission(permissionId);
		java.util.HashMap map = new java.util.LinkedHashMap();
		for (User user : users) {
			map.put(user.getId(), user.getName());
		}
		return map;
	}
	
	  // 获取草稿
	    public List<Manuscript> getDrafts(){
	        Criteria c = dao.initCriteria(Manuscript.class);
	        c.add(Restrictions.eq("user.id", curUser().getId()));
	        c.add(Restrictions.eq("auditZt", Manuscript.STATUS_DRAFT));
	        return c.list();
	    }

	    public List<Manuscript> getBacks(){
	        Criteria c = dao.initCriteria(Manuscript.class);
	        c.add(Restrictions.eq("user.id", curUser().getId()));
	        c.add(Restrictions.eq("auditZt", Manuscript.STATUS_KILLED));
	        return c.list();
	    }
}
